package com.fanqwz.hexieshe.data.common.gsonAdapter;

import com.fanqwz.hexieshe.data.common.entity.Link;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by fanqw on 2017/3/12.
 */

public class LinkTypeAdapter extends TypeAdapter<Link> {
    @Override
    public void write(JsonWriter out, Link value) throws IOException {
        if (null == value)
            out.nullValue();
        else
            out.value(value.getUrl().toString());
    }

    @Override
    public Link read(JsonReader in) throws IOException {
        Link link = new Link();
        try {
            link.setUrl(new URI(in.nextString()).toURL());
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
        return link;
    }
}
